import { UPLOADS_DIR } from "$lib/utils/paths";
import fs from "fs";
import path from "path";
import { randomUUID } from "crypto";

export async function POST({ request }) {
  try {
    const formData = await request.formData();
    const files = formData.getAll("files");
    if (!files || files.length === 0) { return new Response(JSON.stringify({ error: "No files uploaded" }), { status: 400 }); }
    if (files.length > 12) { return new Response(JSON.stringify({ error: "Maximum 12 files allowed per upload" }), { status: 400 }); }
    const savedFiles = [];
    for (const file of files) {
      if (typeof file === "string") continue;
      if (!file.type.startsWith("image/") && !file.type.startsWith("video/") && !file.type.startsWith("audio/")) { return new Response(JSON.stringify({ error: "Only image, video, or audio files allowed" }), { status: 400 }); }
      const buffer = Buffer.from(await file.arrayBuffer());
      const ext = path.extname(file.name);
      const baseName = path.basename(file.name, ext);
      const uniqueName = `${baseName}-${Date.now()}-${randomUUID()}${ext}`;
      const savePath = path.join(UPLOADS_DIR, uniqueName);
      fs.writeFileSync(savePath, buffer);
      savedFiles.push({ originalName: file.name, filename: uniqueName, mimetype: file.type, size: file.size, url: `/api/files/${uniqueName}` });
    }
    return new Response(JSON.stringify({ success: true, files: savedFiles }), { headers: { "Content-Type": "application/json" } });
  } catch (err) {
    return new Response(JSON.stringify({ error: err.message }), { status: 500 });
  }
}
